package com.seqb.common.task;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.config.RedisConfig;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import com.seqb.utils.JsonUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author lilinshen
 * @title 东东萌宠定时任务
 * @description 请填写相关描述
 * @date 2020/5/6
 */
@Component
public class DongdongMengChongJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(DongdongMengChongJob.class);
    public static final HttpHeaders headers = new HttpHeaders();

    static {
        List<String> cookieList = new ArrayList<>();
        cookieList.add("wq_auth_token=C5F43BA319865AC7E311BC9FE0A9E41E1B1464604A55EDF21402AA6EADBA7F94");
        headers.put("Cookie", cookieList);
    }

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            Object taskParams = redisUtils.get("taskParams");
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("DongdongMengChongJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            List<String> cookieList = new ArrayList<>();
                            cookieList.add(jsonObject.getString("key") + "=" + jsonObject.getString("value"));
                            headers.put("Cookie", cookieList);
                        }
                    }
                }
            }
            LOGGER.info("东东萌宠定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            //执行任务
            boolean flag = taskList();

            if (!flag) {
                LOGGER.info("东东萌宠定时任务，执行失败。");
            }

            //记录是否失效
            Object flagRedis = redisUtils.get(RedisConfig.COM_PREFIX + this.getClass().getSimpleName());
            if (!flag && null == flagRedis) {
                //设置一天失效时间的key，每天只发一次邮件通知
                redisUtils.set(RedisConfig.COM_PREFIX + this.getClass().getSimpleName(), true, 86400);
                //发送邮件通知东东萌宠定时任务失效
                MailUtil.send("lilinshen@cecjx.com", "东东萌宠定时任务", "东东萌宠定时任务，用户cookie失效，请及时更新用户cookie信息。", false);
            }

            LOGGER.info("东东萌宠定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 任务列表
     */
    public boolean taskList() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=taskInit&appid=wh5&loginType=1&loginWQBiz=pet-town";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                JSONObject result = JSON.parseObject(entityBody).getJSONObject("result");
                String code = JSON.parseObject(entityBody).getString("code");
                if (!"0".equals(code)) {
                    return false;
                }

                //每天签到任务操作
                JSONObject signInit = result.getJSONObject("signInit");
                Boolean finished = signInit.getBoolean("finished");
                if (!finished) {
                    perSignIn();
                }

                //浏览商品任务操作
                liulanShop(result);

                //获取三餐的水操作
                JSONObject threeMealInit = result.getJSONObject("threeMealInit");
                finished = threeMealInit.getBoolean("finished");
                if (!finished) {
                    getThreeMealWater();
                }

                //喂食狗粮操作
                feedPets();

                //领取能量操作
                getEnergy();

                //助力邀请结束
                inviteFinished();

                //助力好友操作
                helpOqh();

                //好友助力我
                helpMySelf();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 领取能量操作
     */
    public boolean getEnergy() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=energyCollect&appid=wh5&loginType=1&loginWQBiz=pet-town&body={body}";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> commonMap = new HashMap<>();
            for (int i = 1; i <= 5; i++) {
                commonMap.put("place", i);
                HttpEntity httpEntity = new HttpEntity(null, headers);
                ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class, JsonUtils.beanToJson(commonMap));
                HttpStatus status = responseEntity.getStatusCode();
                if (status.equals(HttpStatus.OK)) {
                    String entityBody = responseEntity.getBody();
                    LOGGER.info("领取能量操作：" + entityBody);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 浏览商品任务操作
     *
     * @param jsonObject
     */
    public boolean liulanShop(JSONObject jsonObject) {
        try {
            JSONObject browseSingleShopInit = jsonObject.getJSONObject("browseSingleShopInit");
            Boolean finished = browseSingleShopInit.getBoolean("finished");
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            String requestUrl = "https://api.m.jd.com/client.action?functionId=getSingleShopReward&appid=wh5&loginType=1&loginWQBiz=pet-town&body={body}";
            Map<String, Object> commonMap = new HashMap<>();
            for (int i = 0; i < 5; i++) {
                commonMap.put("index", i);
                commonMap.put("version", "1");
                commonMap.put("type", "1");
                //浏览
                ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class, JsonUtils.beanToJson(commonMap));
                HttpStatus status = responseEntity.getStatusCode();
                if (status.equals(HttpStatus.OK)) {
                    String entityBody = responseEntity.getBody();
                    LOGGER.info("浏览商品任务--浏览操作：" + entityBody);
                }

                commonMap.put("type", "2");
                //领取
                responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class, JsonUtils.beanToJson(commonMap));
                status = responseEntity.getStatusCode();
                if (status.equals(HttpStatus.OK)) {
                    String entityBody = responseEntity.getBody();
                    LOGGER.info("浏览商品任务--领取操作：" + entityBody);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 每天签到任务操作
     */
    public boolean perSignIn() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=getSignReward&appid=wh5&loginType=1&loginWQBiz=pet-town";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                LOGGER.info("每天签到任务操作：" + entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                String code = result.getString("code");
                if (!"0".equals(code)) {
                    return false;
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 喂食狗粮操作
     */
    public boolean feedPets() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=feedPets&appid=wh5&loginType=1&loginWQBiz=pet-town";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                LOGGER.info("喂食狗粮操作：" + entityBody);
                JSONObject result = JSON.parseObject(entityBody).getJSONObject("result");
                String code = JSON.parseObject(entityBody).getString("code");
                if (!"0".equals(code)) {
                    return false;
                }
                if (null != result && null != result.get("foodAmount")) {
                    Long foodAmount = result.getLong("foodAmount");
                    Long frequency = foodAmount / 10;
                    for (int i = 0; i < frequency; i++) {
                        restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
                    }
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 邀请助力结束操作
     */
    public boolean inviteFinished() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=getHelpAddedBonus&appid=wh5&loginType=1&loginWQBiz=pet-town";
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                LOGGER.info("邀请助力结束操作：" + entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                String code = result.getString("code");
                if ("0".equals(code)) {
                    return true;
                }
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 助力好友操作
     */
    public boolean helpOqh() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=slaveHelp&appid=wh5&loginType=1&loginWQBiz=pet-town&body={body}";
            Map<String, Object> commonMap = new HashMap<>();
            commonMap.put("shareCode", "MTAxODc2NTEzMzAwMDAwMDAwNDc5NzQ0Mw==");
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class, JsonUtils.beanToJson(commonMap));
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                LOGGER.info("助力好友操作：" + entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                String code = result.getString("code");
                if ("0".equals(code)) {
                    return true;
                }
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 助力自己操作
     */
    public boolean helpMySelf() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=slaveHelp&appid=wh5&loginType=1&loginWQBiz=pet-town&body={body}";
            Map<String, Object> commonMap = new HashMap<>();
            commonMap.put("shareCode", "MTAxODc2NTEzMjAwMDAwMDAwMDQxNTgzMQ==");
            HttpMethod httpMethod = HttpMethod.GET;
            for (int i = 0; i < 1; i++) {
                List<String> cookieList = new ArrayList<>();
                HttpHeaders headers = new HttpHeaders();
                if (i == 0) {
                    //冬妮助力我
                    cookieList.add("wq_auth_token=481E8645B797102F928FE96D201B707D235E02BA719CF626D1A215D4F5F0EDFE");
                    headers.put("Cookie", cookieList);
                }
                HttpEntity httpEntity = new HttpEntity(null, headers);
                ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class, JsonUtils.beanToJson(commonMap));
                HttpStatus status = responseEntity.getStatusCode();
                if (status.equals(HttpStatus.OK)) {
                    String entityBody = responseEntity.getBody();
                    LOGGER.info("助力自己操作：" + entityBody);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取三餐的水操作
     */
    public boolean getThreeMealWater() {
        try {
            String requestUrl = "https://api.m.jd.com/client.action?functionId=getThreeMealReward&appid=wh5&loginType=1&loginWQBiz=pet-town";
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                LOGGER.info("获取三餐的水操作：" + entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                String code = result.getString("code");
                if ("0".equals(code)) {
                    return true;
                }
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
